<template>
	<view class="topic-detail-page">
		<uni-page-header title="帖子详情" :left-icon="leftIcon" @leftClick="leftClick" />
		<view v-if="detailData" class="">
			<view class="base-info-wrap">
				<u-swiper circular indicator radius="8" height="194" duration="1000" interval="5000" key-name="imageUrl"
					:list="detailData.imgList" indicator-mode="dot" indicator-active-color="#78ffe6" @click="preview" />
				<!--  <view class="img-list">
    	    <image
    	      v-for="(img, img_idx) in detailData.imgList"
    	      :key="img_idx"
    	      lazy-load
    	      :src="img"
    	      class="img"
    	      @click="onPreview(img)"
    	    />
    	  </view> -->
				<view class="name">#{{ detailData.name }}</view>
				<view class="content">{{ detailData.content }}</view>
				<view class="subject-name">{{ detailData.subject_name }}</view>
				<view class="created-time">发布于：{{ $utils.dateFormat(detailData.create_date, 'YYYY-MM-DD') }}</view>
				<view v-if="detailData.address" class="address">
					<u-icon name="map" color="#999" size="18" />
					<view class="value">{{ detailData.address }}</view>
				</view>
			</view>
		</view>

		<view class="fixed-footer__placeholder" />
		<view v-if="detailData" class="fixed-footer">
			<view class="account-info">
				<view class="avatar-wrap">
					<u-avatar :src="detailData.avatar" size="30" />
				</view>
				<view class="nickname">
					<text>{{ detailData.customer_name }}</text>
					<text class="tag">{{ detailData.level_name }}</text>
				</view>
			</view>

			<view class="action-wrap">
				<view class="btn-wrap" @click="onLike">
					<u-icon name="thumb-up" :color="detailData.is_like ? '#ffbf36' : '#7f7f7f'" size="24" />
					<view class="num">{{ detailData.like_num || 0 }}</view>
				</view>
				<view class="btn-wrap" @click="onFavorite">
					<u-icon name="star" :color="detailData.is_favorite ? '#ffbf36' : '#7f7f7f'" size="24" />
					<view class="num">{{ detailData.favorite_num || 0 }}</view>
				</view>
				<view class="btn-wrap" @click="readyToShare">
					<u-icon name="share-square" color="#7f7f7f" size="24" />
					<view class="num">{{ detailData.share_num || 0 }}</view>
				</view>
			</view>
		</view>

		<div v-if="canvasShow" class="shade" catchtouchmove="return" @click="canvasShow = false">
			<div class="qr-code" @click.stop="canvasShow = true">
				<canvas id="qrCanvas" class="qr-canvas" canvas-id="qrCanvas" type="2d" />
			</div>
		</div>
		<div v-if="canvasShow" class="funButton">
			<div class="funItem" @click="shareFriend">
				<button open-type="share" class="funWord" style="
	        margin-top: 0;
	        margin-bottom: 0;
	        border-radius: 50%;
	        padding: 0;
	        height: 80rpx;
	      " @click="readyToShare2">
					<img :src="downloadImg" alt="" class="funImg" mode="widthFix">
				</button>
				<div style="margin-top: 24rpx" class="funWord">分享给好友</div>
			</div>
			<div class="funItem" @click="download">
				<img :src="wechatImg" alt="" class="funImg" mode="widthFix">
				<div class="funWord">保存到相册</div>
			</div>
		</div>
		<view v-if="!isLogin" class="login-mask">
			<get-phone />
		</view>
	</view>
</template>

<script>
	import config from '../config'
	import {
		mapState
	} from 'vuex'
	import {
		wx_talk_subject_post_data,
		wx_talk_subject_post_like,
		wx_talk_subject_post_favorite,
		wx_customer_share_upd,
		wx_customer_share_prefetch,
		wx_customer_click_add
	} from '../api/index'
	import {
		getImg,
		getImgs,
		getSelectQurey,
		encodeQueryData
	} from '../utils/index'

	import shareMixin from '../mixins/shareMixin'

	export default {
		name: 'ArticleDetail',
		mixins: [shareMixin],
		data() {
			return {
				detailData: null,
				id: null,
				canvasShow: false,
				downloadImg: `https://crm.fwh1988.cn/miniapp-imgs/wechat.png`,
				wechatImg: `https://crm.fwh1988.cn/miniapp-imgs/download.png`
			}
		},
		computed: {
			...mapState(['userInfo', 'defaultInfo', 'isLogin']),
			leftIcon() {
				const pages = getCurrentPages()
				if (pages.length === 1) {
					return 'home'
				} else {
					return 'arrow-left'
				}
			}
		},
		onLoad(options) {
			// 帖子转发
			if (options.scene && decodeURIComponent(options.scene).startsWith('@')) {
				const scene = decodeURIComponent(options.scene)

				const matchArr = scene.match(/@(\S+)/)
				const params = {}
				if (matchArr && matchArr[1]) {
					matchArr[1].split('&').forEach(function(pair) {
						let [key, value] = pair.split('=')
						params[decodeURIComponent(key)] = decodeURIComponent(value)
					})
					wx_customer_click_add({
						share_id: parseInt(params.si)
					})
					this.id = parseInt(params.id)
				}
			}
			if (options.share_id) {
				wx_customer_click_add({
					share_id: parseInt(options.share_id)
				})
			}
			if (options.id) {
				this.id = options.id
			}
			this.getDetailData()
		},
		methods: {
			leftClick() {
				if (this.leftIcon === 'home') {
					wx.switchTab({
						url: '/pages/home'
					})
				}
			},
			handleShareInfo() {
				const promise = new Promise((resolve, reject) => {
					wx_customer_share_prefetch({
						type: 10,
						source_id: 22,
						source_out_id: this.id
					}).then(res => {
						wx_customer_share_upd({
							share_id: res.share_id,
							type: 10,
							source_id: 22,
							source_out_id: this.id
						})
						resolve({
							path: `pagesArticle/detail?share_id=${res.share_id}&id=${this.id}`
						})
					})
				})
				return {
					promise
				}
			},
			async createCanvas() {
				function drawText(ctx, text, x, y, width, fwidth, fheight) {
					const lineNum = Math.ceil((text.length * fwidth) / width)
					const oneLineNum = Math.floor(width / fwidth)
					let start = 0
					let end = oneLineNum
					let cursor = 0
					for (let i = 0; i < lineNum; i++) {
						ctx.fillText(text.slice(start, end), x, y + fheight * i)
						cursor = y + fheight * i
						start = end
						end = end + oneLineNum
					}
					return cursor
				}
				const query = await getSelectQurey('#qrCanvas')
				const qrCanvas = query[0].node
				const ctx = qrCanvas.getContext('2d')
				const {
					pixelRatio
				} = wx.getSystemInfoSync()
				qrCanvas.width = query[0].width * pixelRatio
				qrCanvas.height = query[0].height * pixelRatio
				ctx.fillStyle = '#ffffff'
				ctx.fillRect(0, 0, qrCanvas.width, qrCanvas.height)
				let image = qrCanvas.createImage()
				this.bgImg = getImg(this.detailData.image)
				image.src = getImg(this.detailData.image)
				image.onload = () => {
					const imageRadio =
						((query[0].width - 12 * pixelRatio) / image.width) * pixelRatio
					ctx.drawImage(
						image,
						12 * pixelRatio,
						12 * pixelRatio,
						image.width,
						image.width * 0.5,
						12 * pixelRatio,
						12 * pixelRatio,
						qrCanvas.width - 12 * pixelRatio,
						(qrCanvas.width - 12 * pixelRatio) * 0.5
					)

					let avatarImg = qrCanvas.createImage()
					if (!this.detailData.avatar || (this.detailData.avatar && !this.detailData.avatar
							.startsWith(
								'http'))) {
						if (this.defaultInfo.avatar) {
							this.detailData.avatar = this.defaultInfo.avatar
						}
					}
					avatarImg.src = this.detailData.avatar
					avatarImg.onload = async () => {
						ctx.drawImage(
							avatarImg,
							12 * pixelRatio,
							qrCanvas.width - 150 * pixelRatio + 20 * pixelRatio,
							32 * pixelRatio,
							32 * pixelRatio
						)

						ctx.font = 14 * pixelRatio + 'px PingFangSC-Semibold, PingFang SC'
						ctx.fillStyle = '#333333'
						ctx.fillText(
							this.detailData.customer_name,
							52 * pixelRatio,
							qrCanvas.width - 150 * pixelRatio + 40 * pixelRatio
						)

						const nameWidth = ctx.measureText(
							this.detailData.customer_name
						).width

						ctx.font = 14 * pixelRatio + 'px PingFangSC-Semibold, PingFang SC'
						ctx.fillStyle = '#333333'
						ctx.fillText(
							this.detailData.level_name,
							58 * pixelRatio + nameWidth,
							qrCanvas.width - 150 * pixelRatio + 40 * pixelRatio
						)

						ctx.font =
							14 * pixelRatio + 'px SourceHanSansCNVF-Regular, SourceHanSansCNVF'
						ctx.fillStyle = 'rgba(0, 0, 0, 0.9)'
						let topic_cursor2 = 108
						let a = ''
						if (this.detailData.content.length >= 50) {
							a = '...'
						}
						ctx.font =
							14 * pixelRatio + 'px SourceHanSansCNVF-Regular, SourceHanSansCNVF'
						ctx.fillStyle = 'rgba(0, 0, 0, 0.9)'
						drawText(
							ctx,
							`${this.detailData.content.slice(0, 50) + a}`,
							12 * pixelRatio,
							qrCanvas.width - 150 * pixelRatio + topic_cursor2 * pixelRatio,
							qrCanvas.width - 24 * pixelRatio,
							14 * pixelRatio,
							20 * pixelRatio
						)
						ctx.font =
							16 * pixelRatio + 'px SourceHanSansCNVF-Medium, SourceHanSansCNVF'
						ctx.fillStyle = '#00584A'
						let topic_cursor = 108

						if (
							ctx.measureText(this.detailData.subject_name).width < qrCanvas.width
						) {
							ctx.fillText(
								`#${this.detailData.subject_name}`,
								12 * pixelRatio,
								qrCanvas.width - 150 * pixelRatio + 170 * pixelRatio
							)
						} else {
							drawText(
								ctx,
								`${this.detailData.subject_name}`,
								12 * pixelRatio,
								qrCanvas.width - 150 * pixelRatio + 170 * pixelRatio,
								qrCanvas.width - 24 * pixelRatio,
								14 * pixelRatio,
								20 * pixelRatio
							)
							topic_cursor += 20
						}

						ctx.font =
							14 * pixelRatio + 'px SourceHanSansCNVF-Regular, SourceHanSansCNVF'
						ctx.fillStyle = 'rgba(0, 0, 0, 0.99)'
						ctx.font = 'normal bold 46px sans-serif'

						let arr2 = ''
						if (this.detailData.name.length > 13) {
							arr2 = '...'
						}
						let cursor = drawText(
							ctx,
							`${this.detailData.name.slice(0, 13) + arr2}`,
							12 * pixelRatio,
							qrCanvas.width - 150 * pixelRatio + 80 * pixelRatio,
							qrCanvas.width - 24 * pixelRatio,
							14 * pixelRatio,
							20 * pixelRatio
						)

						const token = wx.getStorageSync('token')

						let tymImage = qrCanvas.createImage()
						let obj = {
							'env_version': process.env.NODE_ENV === 'development' ? 'develop' :
								'release',
							'page': 'pagesArticle/detail',
							'check_path': false
						}

						const shareRes = await wx_customer_share_prefetch({
							type: 10,
							source_id: 22,
							source_out_id: this.id
						})

						await wx_customer_share_upd({
							'share_id': shareRes.share_id, // 分享id
							'type': 10, // 分享类型(1:分享好友,2:图片分享)
							'source_id': 22, // 来源类型
							'source_out_id': this.id // 内容ID/编码
						})
						const scene = encodeURIComponent('@' + encodeQueryData({
							id: this.id,
							si: shareRes.share_id
						}))
						console.log('参数-->', scene)
						tymImage.src =
							`https://crm.sfuture100.com/action/apimanager/exec?_name=api_get_wxacode&token=${token}&account_no=${config.PASS.account_no}&scene=${scene}&${encodeQueryData(obj)}`

						tymImage.onload = () => {
							console.log('图片加载成功')
							ctx.drawImage(
								tymImage,
								12 * pixelRatio,
								cursor + 112 * pixelRatio,
								72 * pixelRatio,
								72 * pixelRatio
							)
							ctx.font =
								14 * pixelRatio +
								'px SourceHanSansCNVF-Medium, SourceHanSansCNVF'
							ctx.fillStyle = '#00584A'
							ctx.fillText(
								'青丝几何',
								90 * pixelRatio,
								cursor + 144 * pixelRatio
							)

							ctx.font =
								12 * pixelRatio +
								'px SourceHanSansCNVF-Medium, SourceHanSansCNVF'
							ctx.fillStyle = '#969799'
							ctx.fillText(
								'长按二维码，识别完整内容',
								90 * pixelRatio,
								cursor + 164 * pixelRatio
							)
							console.log('canva赋值成功-->', qrCanvas)
							this.qrCanvas = qrCanvas
						}
					}
				}
			},
			readyToShare() {
				this.canvasShow = true
				this.$nextTick(() => {
					this.createCanvas()
				})
			},
			download() {
				const qrCanvas = this.qrCanvas
				const self = this
				wx.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: qrCanvas.width,
					height: qrCanvas.height,
					destWidth: qrCanvas.width,
					destHeight: qrCanvas.height,
					canvasId: 'qrCanvas',
					canvas: qrCanvas,
					success(res) {
						self.canvasShow = false
						wx.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(albumRes) {
								wx.showToast({
									title: '下载成功',
									icon: 'success',
									duration: 2000
								})
							}
						})
					}
				})
			},
			shareFriend() {
				this.canvasShow = false
			},
			readyToShare2() {
				this.canvasShow = false
			},

			async getDetailData() {
				const data = await wx_talk_subject_post_data({
					post_id: +this.id
				})
				console.log('帖子详情')
				console.log(data)
				this.detailData = data.post_data
				this.$set(this.detailData, 'imgList', getImgs(data.post_data.image))
			},
			preview(index) {
				wx.previewImage({
					urls: this.detailData.imgList,
					current: this.detailData.imgList[index]
				})
			},
			onPreview(imgSrc) {
				this.$utils.previewImg([imgSrc])
			},
			// 点赞
			async onLike() {
				const {
					id,
					is_like
				} = this.detailData
				const params = {
					post_id: id,
					is_enable: is_like ? false : true
				}
				await wx_talk_subject_post_like(params)
				this.getDetailData()
				// this.detailData.is_like = !this.detailData.is_like
			},

			// 收藏
			async onFavorite() {
				const {
					id,
					is_favorite
				} = this.detailData
				const params = {
					post_id: id,
					is_enable: is_favorite ? false : true
				}
				await wx_talk_subject_post_favorite(params)
				this.getDetailData()
				// this.detailData.is_favorite = !this.detailData.is_favorite
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-mask {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
	}

	.topic-detail-page {
		width: 90%;
		margin: 20rpx auto;
		position: relative;

		.base-info-wrap {
			padding: 26rpx;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			background-color: #FFF;

			.img-list {
				@include flex-column-center;
				gap: calc(8% / 3);
				flex-wrap: wrap;

				.img {
					width: 23%;
					height: 160rpx;
					border-radius: 10rpx;
					margin-top: 15rpx;
				}
			}

			.name {
				font-size: 28rpx;
				font-weight: 600;
				padding-top: 20rpx;
			}

			.content {
				margin: 20rpx 0;
				font-size: 24rpx;
			}

			.subject-name {
				width: max-content;
				padding: 5rpx 10rpx;
				background-color: #FFF36D;
				border-radius: 50rpx;
				font-size: 24rpx;
			}

			.created-time {
				font-size: 24rpx;
				padding-top: 24rpx;
			}

			.address {
				font-size: 26rpx;
				padding-top: 20rpx;
				display: flex;
				gap: 10rpx;
				align-items: flex-start;
			}
		}

		.fixed-footer {
			width: 100%;
			height: 130rpx;
			padding: 0 20rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			background-color: #FFF;
			@include flex-between;

			&__placeholder {
				width: 100%;
				height: 130rpx;
			}

			.account-info {
				@include flex-column-center;
				gap: 10rpx;

				.avatar-wrap {
					z-index: 1;
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					background-color: #FFF;
					@include flex-center;
				}

				.nickname {
					margin-left: -25rpx;
					font-size: 28rpx;
					padding: 10rpx;
					padding-left: 30rpx;
					border-radius: 50rpx;
					background-color: #F3F3F3;

					.tag {
						color: #039076;
						padding-left: 8rpx;
					}
				}
			}

			.action-wrap {
				@include flex-column-center;
				gap: 20rpx;

				.btn-wrap {
					@include flex-column-center;

					.num {
						font-size: 26rpx;
						color: rgba(0, 0, 0, 0.5);
					}
				}
			}
		}
	}

	.funButton {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 186rpx;
		background: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		z-index: 101;

		.funItem {
			flex: 1;
			display: flex;
			flex-flow: column nowrap;
			align-items: center;

			.funImg {
				width: 78rpx;
			}

			.funWord {
				font-size: 28rpx;

				font-weight: 400;
				color: #323233;
				line-height: 40rpx;
				margin-top: 24rpx;
			}
		}
	}

	.shade {
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.6);
		position: fixed;
		z-index: 100;
		top: 0;
		left: 0;

		.qr-code {
			width: 638rpx;
			height: 902rpx;
			background-color: #fff;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -60%);

			/* margin: 30rpx auto; */
			.qr-canvas {
				display: block;
				background-color: #fff;
				margin: 0 auto;
				width: 638rpx;
				height: 902rpx;
			}
		}
	}
</style>